<!--
 * @Description:
 * @Date: 2024-06-25 21:24:10
 * @LastEditTime: 2024-08-06 11:11:41
-->
<!-- 使用 type="home" 属性设置首页，其他页面不需要设置，默认为page；推荐使用json5，更强大，且允许注释 -->
<route lang="json5" type="page" needLogin="false">
{
  style: {
    navigationBarTitleText: '',
  },
}
</route>
<template>
  <view class="bg-white overflow-hidden w-100% box-border">
    <view>
      <wd-form ref="form" :model="model" :rules="rules">
        <wd-cell title="景点图片（图片）" vertical prop="files">
          <wd-upload
            required
            :file-list="model.files"
            :limit="6"
            multiple
            name="file"
            image-mode="aspectFill"
            :action="actions"
            @change="handleFileChange"
            @success="handleChange"
            @remove="handleRemove"
            class="bg-#fff"
          ></wd-upload>
        </wd-cell>
        <wd-cell title="景点名称" vertical prop="scenicName">
          <wd-input
            v-model="model.scenicName"
            :maxlength="20"
            :show-word-limit="true"
            placeholder="例如：乡村研学趣味园"
          />
        </wd-cell>
        <wd-cell title="景点标签" vertical prop="scenicLabel">
          <wd-tag
            v-model="model.scenicLabel"
            v-for="(tag, index) in tags"
            :key="index"
            custom-class="space"
            round
            closable
            @close="handleClose(index)"
          >
            {{ tag }}
          </wd-tag>
          <wd-tag
            v-if="tags.length < 6"
            custom-class="space"
            round
            dynamic
            @confirm="handleConfirm"
          ></wd-tag>
        </wd-cell>
        <wd-cell title="地址" vertical prop="scenicAddr">
          <view
            class="bg-#1F6977 text-#fff border-rd-8rpx text-24rpx p-8rpx"
            @click="handleAddr"
            style="position: absolute; top: -42px; left: 50px"
          >
            点击自动获取
          </view>
          <wd-input
            v-model="model.scenicAddr"
            :maxlength="50"
            :show-word-limit="true"
            placeholder="请填写详细地址"
          />
        </wd-cell>
        <wd-cell title="开放时间" vertical prop="openTime">
          <wd-input
            v-model="model.openTime"
            :maxlength="20"
            :show-word-limit="true"
            placeholder="例如：全年 早上8:00-晚上8:00"
          />
        </wd-cell>
        <wd-cell title="人均消费（元）" vertical prop="consumption">
          <wd-input
            v-model="model.consumption"
            :maxlength="20"
            :show-word-limit="true"
            placeholder="例如：100"
          />
        </wd-cell>
        <wd-cell title="联系电话" vertical prop="phone">
          <wd-input
            v-model="model.phone"
            :maxlength="20"
            :show-word-limit="true"
            placeholder="例如：18928743847"
          />
        </wd-cell>
        <wd-cell title="景区简介" vertical prop="introduction">
          <wd-textarea
            v-model="model.introduction"
            :maxlength="200"
            :show-word-limit="true"
            placeholder="例如：景点特色、周边设施、交通信息、注意事项..."
          />
        </wd-cell>
        <wd-cell title="旅游攻略" vertical prop="travelGuide">
          <wd-textarea
            v-model="model.travelGuide"
            :maxlength="200"
            :show-word-limit="true"
            placeholder="例如：最佳游览时间：[推荐适合游玩的季节或时间段]游览路线：[提供一条或多条推荐的游览路线，包括各个活动区域的介绍]注意事项：[提醒游客注意安全、遵守园区规定等事项]"
          />
        </wd-cell>
      </wd-form>
      <view class="question-btn flex items-center justify-between">
        <wd-button plain hairline @click="submitHandler">提交</wd-button>
      </view>
    </view>
  </view>
</template>

<script lang="ts" setup>
import { FormRules } from 'wot-design-uni/components/wd-form/types'
import { useToast } from 'wot-design-uni'
import { cerateAttractions, updateAttractions } from '@/service/TouristManagement/MyAttractions'
import { useUserStore } from '@/store'
import _ from 'lodash'

const userStore = useUserStore()
const toast = useToast()
const baseurl = ref(import.meta.env.VITE_SERVER_BASEURL)
const actions: string = baseurl.value + '/app-api/infra/file/business/upload'
const form = ref()
const showButton = ref(false)
const showType = ref()
const saveId = ref()
const userId = computed(() => userStore.userInfo.userId)
const model = reactive<{
  scenicName: string
  scenicLabel: string
  scenicAddr: string
  openTime: string
  consumption: string
  phone: string
  introduction: string
  travelGuide: string
  files: any[]
}>({
  scenicName: '',
  scenicLabel: '',
  scenicAddr: '',
  openTime: '',
  consumption: '',
  phone: '',
  introduction: '',
  travelGuide: '',
  files: [],
})

const rules: FormRules = {
  scenicName: [
    {
      required: true,
      message: '请输入景点名称',
      validator: (value) => {
        if (value) {
          return Promise.resolve()
        } else {
          return Promise.reject(new Error('景点名称'))
        }
      },
    },
  ],
  scenicLabel: [
    {
      required: true,
      message: '请输入景点标签',
      validator: (value) => {
        if (value) {
          return Promise.resolve()
        } else {
          return Promise.reject(new Error('请输入景点标签'))
        }
      },
    },
  ],
  scenicAddr: [
    {
      required: true,
      message: '请输入地址',
      validator: (value) => {
        value = value.trim()
        if (!value) {
          return Promise.reject('请输入地址')
        }
        if (/^\d+$/.test(value)) {
          return Promise.reject(new Error('地址不能是纯数字'))
        } else {
          return Promise.resolve()
        }
      },
    },
  ],
  openTime: [
    {
      required: true,
      message: '请输入开放时间',
      validator: (value) => {
        if (value) {
          return Promise.resolve()
        } else {
          return Promise.reject(new Error('请输入开放时间'))
        }
      },
    },
  ],
  consumption: [
    {
      required: true,
      message: '请输入人均消费',
      trigger: 'change',
      validator: (value, rule) => {
        value = value.trim()
        if (!value) {
          return Promise.reject(new Error('请输入人均消费'))
        }
        const regex = /^\d+(\.\d{1,2})?$/
        if (!regex.test(value)) {
          return Promise.reject(new Error('小数点后不超过两位'))
        }
        const numValue = parseFloat(value)
        if (isNaN(numValue) || numValue > 1000) {
          return Promise.reject(new Error('人均消费必须是有效的数字且不能超过1000'))
        }

        return Promise.resolve(true)
      },
    },
  ],
  files: [
    {
      value: model.files,
      required: true,
      message: '请输入景点照片',
      validator: (value) => {
        if (value.length) {
          return Promise.resolve()
        } else {
          return Promise.reject('请输入景点照片')
        }
      },
    },
  ],
  phone: [
    {
      required: true,
      message: '请输入联系电话',
      validator: (value) => {
        value = value.trim()
        if (!value) {
          return Promise.reject(new Error('请输入联系电话'))
        }
        // 使用正则表达式验证手机号码格式
        const regex = /^1(3|4|5|6|7|8|9)\d{9}$/
        if (!regex.test(value)) {
          return Promise.reject(new Error('手机号码格式不正确'))
        }
        return Promise.resolve(true)
      },
    },
  ],
  introduction: [
    {
      required: true,
      message: '请输入景区简介',
      validator: (value) => {
        if (value) {
          return Promise.resolve()
        } else {
          return Promise.reject(new Error('请输入景区简介'))
        }
      },
    },
  ],
}
defineOptions({
  name: 'addAtttactions',
})
const longitude = ref()
const latitude = ref()
const latAndLon = ref('')
// 自动获取地址
const handleAddr = async () => {
  uni.getLocation({
    type: 'wgs84',
    success: (res) => {
      longitude.value = res.longitude
      latitude.value = res.latitude
      latAndLon.value = longitude.value + ',' + latitude.value
      const key = '3a03083007a21041fa2cea8bffdca493' // 替换为你的API密钥
      const url = `https://restapi.amap.com/v3/geocode/regeo?output=JSON&location=${longitude.value},${latitude.value}&key=${key}`
      uni.request({
        url,
        method: 'GET',
        success: (res) => {
          if (res.statusCode === 200) {
            const data = res.data
            if (data.status === '1' && data.regeocode) {
              const geocode = data.regeocode
              const address = geocode.formatted_address
              model.scenicAddr = address
            } else {
              console.error('获取地址失败：', data.info)
            }
          } else {
            console.error('请求失败：', res.statusCode)
          }
        },
        fail: (err) => {
          console.error('请求失败：', err)
        },
      })
    },
    fail: (err) => {
      console.error('获取位置失败：', err)
    },
  })
}
// 获取经纬度
const getLatAndLon = async () => {
  const key = '3a03083007a21041fa2cea8bffdca493' // 替换为你的API密钥
  const url = `https://restapi.amap.com/v3/geocode/geo?key=${key}&address=${encodeURIComponent(model.scenicAddr)}`
  try {
    const res = await new Promise((resolve, reject) => {
      uni.request({
        url,
        method: 'GET',
        success: (res) => {
          if (res.statusCode === 200) {
            resolve(res.data)
          } else {
            reject(new Error('请求失败：' + res.statusCode))
          }
        },
        fail: (err) => {
          reject(new Error('请求失败：' + err))
        },
      })
    })

    const data = res
    console.log(data, 'data')
    if (data.status === '1' && data.geocodes[0]) {
      latAndLon.value = data.geocodes[0].location
    } else {
      console.error('获取地址失败：', data.info)
      throw new Error('获取地址失败：' + (data.info || '未知错误'))
    }
  } catch (error) {
    console.error('获取地址过程中发生错误：', error)
    throw error
  }
}
// latAndLon
function handleChange({ file }) {
  const { response } = file
  const fileId = JSON.parse(response).data.id
  file.fileId = fileId
  model.files.push(file)
}
function handleFileChange({ fileList }) {
  // console.log(fileList, 'fileList')
  //   model.fileList = fileList
}
function handleRemove({ file }) {
  model.files = model.files.filter((item) => {
    return item.uid !== file.uid
  })
}
// 标签
const tags = ref([])

function handleClose(order) {
  tags.value = tags.value.filter((value, index) => index !== order)
}

function handleConfirm({ value }) {
  if (!value) return
  tags.value = [...tags.value, value]
}
const idList = ref([])

const submitHandler = _.debounce(
  () => {
    handleSubmit()
  },
  1000,
  { leading: true },
)

const handleSubmit = async () => {
  model.scenicLabel = tags.value.join(',')

  const fileIds = ref([])
  // eslint-disable-next-line array-callback-return
  model.files.forEach((item) => {
    if (item.fileId) {
      fileIds.value.push(item.fileId)
    }
    if (item.id) {
      fileIds.value.push(item.id)
    }
  })
  const newFilesSet = [...new Set(fileIds.value)]
  idList.value = newFilesSet
  try {
    const { valid, errors } = await form.value.validate()
    if (!valid) {
      toast.error({ msg: '请检查必选项是否填写', duration: 2000 })
      return
    }
    await getLatAndLon()
    const creatorVo = {
      userId: userId.value,
    }
    const apiCall = showType.value === 'add' ? cerateAttractions : updateAttractions
    // 调用API
    try {
      await apiCall({
        ...model,
        ...creatorVo,
        id: saveId.value,
        files: idList.value,
        latAndLon: latAndLon.value,
      })
      toast.success({ msg: '操作成功', duration: 2000 })
      setTimeout(() => {
        uni.navigateBack({ delta: 1 })
        toast.close()
      }, 1000)
    } catch (error) {
      toast.error({ msg: '提交失败', duration: 2000 })
    }
  } catch (validationError) {
    console.error('验证过程发生错误:', validationError)
    toast.error({ msg: '表单验证异常', duration: 2000 })
  }
}

onLoad((options) => {
  showType.value = options.type
  if (options.type === 'edit') {
    const item = JSON.parse(decodeURIComponent(options.data || '{}'))
    saveId.value = item.id
    model.scenicName = item.scenicName
    tags.value = item.scenicLabel
    model.scenicAddr = item.scenicAddr
    model.openTime = item.openTime
    model.consumption = item.consumption
    model.phone = item.phone
    model.travelGuide = item.travelGuide || ''
    model.introduction = item.introduction
    model.files = item.fileDOList.map((val) => {
      return { ...val, url: baseurl.value + val.url }
    })
  }
})
</script>

<style lang="scss" scoped>
.videoCard {
  background: rgba(0, 0, 0, 0.04);
}
::v-deep .wd-icon-sound {
  margin-right: 20rpx;
}
::v-deep .wd-textarea {
  padding: 0 !important;
}
::v-deep .wd-textarea::after,
::v-deep .wd-input::after {
  height: 0 !important;
}

::v-deep .wd-textarea__value,
::v-deep .wd-input__value {
  padding: 20rpx !important;
  background: #f3f4f7 !important;
}
::v-deep .wd-textarea__count,
::v-deep .wd-input__count {
  right: 20rpx !important;
  background: #f3f4f7 !important;
}
::v-deep .wd-cell__title {
  font-weight: bold !important;
  color: #333 !important;
}
::v-deep .wd-cell__right {
  margin-top: 20rpx !important;
}
::v-deep .wd-button {
  background: #029669 !important;
}
::v-deep .wd-tag.is-default.is-round {
  border-radius: var(--wot-tag-round-radius, 8rpx) !important;
  line-height: 32rpx !important;
}
::v-deep .wd-tag.is-default.is-round:hover {
  color: #ad0e0e !important;
  border-color: #ad0e0e !important;
}
.question-btn {
  height: 100rpx;
  padding: 40rpx !important;
  text-align: center;
  box-shadow: 0px -3px 6px 0px rgba(201, 201, 201, 0.4);
}
.fixed-button {
  position: fixed;
  bottom: 0;
  left: 50%;
  z-index: 99;
  width: 100%;
  transform: translateX(-50%);
}
::v-deep.wd-button.is-plain.is-primary {
  width: 100%;
  border: none !important;
  border-radius: 18rpx !important;
  color: #fff !important;
}
:deep(.space) {
  margin: 0 10rpx 10rpx;
}
::v-deep .wd-tag__close {
  vertical-align: baseline !important;
  line-height: 32rpx !important;
}
::v-deep .wd-tag__add {
  vertical-align: baseline !important;
}
::v-deep .wd-tag__text {
  vertical-align: baseline !important;
}
::v-deep .wd-upload__mask {
  background: transparent !important;
}
</style>
